package com.thinker.interview.dynamic_datasource.dynamic_datasource;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
@Slf4j
public class RegionInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String region = request.getHeader("Region");
        log.info("Region = {}", region);
        if ("SG".equalsIgnoreCase(region)) {
            RegionDataSourceContextHolder.setRegion("SG");
        } else {
            RegionDataSourceContextHolder.setRegion("CN"); // 默认处理
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
                                Object handler, Exception ex) {
        RegionDataSourceContextHolder.clear(); // 请求结束后清理线程变量
    }
}
